package LeetCode._01算法入门.day04双指针;

import org.junit.Test;

/**
 * @author 挚爱之夕
 * @date 2022-02-23 - 02 - 23 - 10:37
 * @Description 给定一个字符串s
 * 反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
 * @Version 简单
 */
public class _557翻转字符串中的单词 {
    static String s = "Let's take LeetCode contest";

    //by me
    @Test
    public void solve(){
        String res = reverseWords(s);
        System.out.println(res);
    }
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < words.length; i++){
            sb.append(reverseWord(words[i]));
            if(i != words.length - 1)
                sb.append(" ");
        }
        return sb.toString();
    }
    public String reverseWord(String word){
        int index = word.length() - 1;
        StringBuilder sb = new StringBuilder();
        while(index >= 0){
            sb.append(word.charAt(index--));
        }
        return sb.toString();
    }
    /*使用指针的思路*/
    public String reverseWords1(String s) {
        int length = s.length();
        int p = 0;
        StringBuilder sb = new StringBuilder();
        while(p < length){
            //记录起始位置
            int start = p;
            //找到第一个空格
            while(p < length && s.charAt(p) != ' '){
                p++;
            }
            //翻转这个单词
            for(int i = p - 1; i >= start; i--){
                sb.append(s.charAt(i));
            }
            //过滤空格
            while(p < length && s.charAt(p) == ' '){
                p++;
                sb.append(" ");
            }
        }
        return sb.toString();
    }
}
